from utils.crawl_tool_for_py3_v6 import crawlerTool
# from utils.qianfan_util import QianFan
import efinance as ef
from MyTT import *
from utils.e_mail import sendMail
from datetime import datetime, timedelta
from utils.log_util import saveLog
from utils.db_util import SqliteTool
from utils.time_util import fmt_d, stamp_time, YYYYMMDD
from constant.param_config import getConfigPath


class BaseStockPrice():

    # 请求n天内的交易数据
    limitAgoDay = 60
    # 最高价限制
    limitMaxPrice = 20
    # 价格限定之外的股票
    testCode = {}
    # kdj买卖分界线
    bottomLimit = 50
    # 最低涨跌幅
    limitMinUp = 0
    #上次检测到的股票
    lastNoticeCode = []

    def __init__(self):
        super().__init__()
        self.request = crawlerTool()
        # self.qianfan = QianFan()

    def initThread(self):
        """
        初始化线程
        """

        tables = [
            "article_stock", "record_stock", "code_stock", "volume_stock"
        ]
        dbPath = getConfigPath() + "\data.db"

        self.sqlite = SqliteTool(dbPath=dbPath)
        self.sqlite.create_table_list(tableName=tables)

    def volumeDB(self, stockList):
        """
        数据库成交量检查
        """

        volumeData = self.sqlite.query_many("SELECT * FROM volume_stock")

        if len(stockList) != 0:
            # 去重
            stockList = list(set(stockList))
            agoStartDay = self.getStockAgoDate(self.limitAgoDay)
            agoEndDay = self.getStockAgoDate(1)

            startDate = fmt_d(agoStartDay, "%Y%m%d")
            endDate = fmt_d(agoEndDay, "%Y%m%d")

            if len(volumeData) != 0:
                self.updateVolume(stockList, agoStartDay, agoEndDay)
            else:
                self.requestHistory(stockList, startDate, endDate)

    def updateVolume(self, stockList, agoStartDay, agoEndDay):
        """
        增量更新成交量
        """

        startDate = fmt_d(agoStartDay, "%Y%m%d")
        endDate = fmt_d(agoEndDay, "%Y%m%d")

        self.refreshDB(stockList, agoStartDay, startDate, endDate)
        allCode = [
            item[0] for item in self.sqlite.query_many(
                "SELECT DISTINCT code FROM volume_stock")
        ]
        agoDayCode = [
            item[0] for item in self.sqlite.query_many(
                "SELECT DISTINCT code FROM volume_stock WHERE date =" +
                str(agoEndDay))
        ]
        notInDayCode = [elem for elem in allCode if elem not in agoDayCode]
        if len(notInDayCode) != 0:
            self.requestHistory(notInDayCode, endDate, endDate)

    def refreshDB(self, stockList, agoStartDay, startDate, endDate):
        """
        刷新数据库
        """

        self.sqlite.delete_record("DELETE FROM volume_stock WHERE date < " +
                                  str(agoStartDay))

        codes = [
            item[0] for item in self.sqlite.query_many(
                "SELECT DISTINCT code FROM volume_stock")
        ]

        # 数据库中存在而api中被过滤时，删除数据库多余数据
        for code in list(set(codes) - set(stockList)):
            self.sqlite.delete_record(
                "DELETE FROM volume_stock WHERE code = " + code)

        # api中新出现，但是数据库没有
        newStock = list(set(stockList) - set(codes))
        if len(newStock) != 0:
            self.requestHistory(newStock, startDate, endDate)
